<?php

class UserController extends Controller {
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'checkLogin', 'checkout', 'sendmail'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array(User::model()->getAdmin()->email),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new User;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('User');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new User('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['User']))
            $model->attributes = $_GET['User'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionCheckLogin() {
        if (Yii::app()->user->isGuest) {
            $this->redirect('site/login');
        } else {
            $userName = Yii::app()->user->name;
            //$role = $userName = Yii::app()->user->admin;
            $userInformation = User::model()->getUserInformation($userName);
            $checkoutUser = new User;
            $this->breadcrumbs[] = Yii::t('default', 'purchase');
            $this->pageTitle = Yii::t('default', 'purchase');
            $this->render('checkout', array(
                'model' => $checkoutUser,
                'userInfo' => $userInformation,
            ));
        }
    }

    /**
     * Displays the checkout page
     */
    public function actionCheckout() {
        $request = Yii::app()->request;
        $userId = $request->getPost('userId');
        $email = $request->getPost('email');
        $name = $request->getPost('name');
        $address = $request->getPost('address');
        $phone = $request->getPost('phone');
        $cartLength = $request->getPost('cartLength');
        $cart = array();
        for ($i = 0; $i < $cartLength; $i++) {
            $item = array();
            $item['productId'] = $request->getPost("productId" . $i);
            $item['productName'] = $request->getPost("productName" . $i);
            $item['productPrice'] = $request->getPost("productPrice" . $i);
            $item['productPromotion'] = $request->getPost("productPromotion" . $i);
            $item['productQty'] = $request->getPost("productQty" . $i);
            $t = $request->getPost("productQty" . $i);
            $cart[] = $item;
        }

        $rowCartContent = '';
        $totalPrice = 0;
        for ($j = 0; $j < count($cart); $j++) {
            $G = $cart[$j];
            $totalPrice = $totalPrice + ($G['productPrice'] * $G['productQty']);
            $rowCartContent = $rowCartContent
                    . '<tr style="height:20px;">'
                    . '<td style="text-align:center;">' . $G['productId'] . '</td>'
                    . '<td style="text-align:center;">' . $G['productName'] . '</td>'
                    . '<td style="text-align:center;">' . number_format($G['productPrice'],0,'','.') . '</td>'
                    . '<td style="text-align:center;">' . $G['productQty'] . '</td>'
                    . '<td style="text-align:center;">' . number_format( ($G['productPrice'] * $G['productQty']) ,0,'','.') . '</td>'
                    . '</tr>';
        }

        //send mail
        $today = date("Y-m-d H:i:s");
        $info = array();
        $info['emailTo'] = $email;
        $info['subject'] = 'Don hang ' . $today;
        //$info['body'] = 'Tên khách hàng:' . $contactForm->name . '\n' . 'Email:' . $contactForm->email . '\n' . $contactForm->body;
        $info['body'] =
                '            
<html>
    <head>     
        <meta charset="UTF-8" />
        <meta name="language" content="vi" />
    </head>
    <body>
        <div style=" border:1px solid #dfdfdf;border-radius:5px;padding:10px;text-align:left;">
            <h3> ĐƠN HÀNG CỦA QUÝ KHÁCH </h3>
            <div>
                <h4>Tên khách hàng: ' . $name . ' </h4>
                <h4>Email: ' . $email . '</h4>
                <h4>Địa chỉ: ' . $address . '</h4> 
                <h4>Điện thoại: ' . $phone . '</h4>
            </div>
            <div>
                <table class="table" border="1">
                    <thead>
                        <tr>
                            <th style="width:200px;">Mã sản phẩm</th>
                            <th style="width:200px;">Tên sản phẩm</th>
                            <th style="width:100px;">Giá(VND)</th>
                            <th style="width:100px;">Số lượng</th>
                            <th style="width:100px;">Tổng tiền(VND)</th>
                        </tr>
                    </thead>
                    <tbody>' . $rowCartContent . '
                    </tbody>
                </table>
            </div>
            <div style="margin-top:10px;">
                Tổng tiền:
                <strong>' . number_format($totalPrice, 0,'','.') . ' VND</strong>
            </div>
        </div>
    </body>
</html>
            
            ';

        $this->sendPhpMailer($info);
        //save infor
        $newCart = new Cart;
        $newCart->user_id = $userId;
        $newCart->total_money = $totalPrice;
        $newCart->send_date = $today;
        $newCart->save();
        $cartId = $newCart->id;

        for ($j = 0; $j < count($cart); $j++) {
            $cartDetail = new CartDetail;
            $C = $cart[$j];
            $cartDetail->cart_id = $cartId;
            $cartDetail->product_id = $C['productId'];
            $cartDetail->product_number = $C['productQty'];
            $cartDetail->product_price = $C['productPrice'];
            $cartDetail->save();
        }
        echo CJSON::encode(array('message' => '<div>
    <h4 style="text-align:left; font-weight: normal;background-color: #ddd;border: 1px solid #ccc; color:#6eac2c;">Đặt hàng thành công. Đơn đặt hàng của bạn đã được gửi đến email của bạn, vui lòng kiềm tra email để xem đầy đủ thông tin. Chúng tôi sẽ sớm liên hệ với bạn sau</h4>
</div>', 'output_html' => $info['body']));

        /* $result = true;
          $this->renderPartial('_checkoutResult', array(
          'result' => $result,
          )); */
    }

    /**
     * send mail with phpmailer
     */
    public function sendPhpMailer($info = array()) {
        require("protected/extensions/phpmailer/class.phpmailer.php");
        $mail = new PHPMailer();
        $mail->IsSMTP(); // send via SMTP
        //IsSMTP(); // send via SMTP
        $mail->SMTPAuth = true; // turn on SMTP authentication
        $mail->Username = "tbtrong2014@gmail.com"; // SMTP username
        $mail->Password = "java789789"; // SMTP password
        $webmaster_email = "tbtrong2014@gmail.com"; //Reply to this email ID     
        $mail->From = $webmaster_email;
        $mail->FromName = "Webmaster";

        $emailTo = $info['emailTo']; // Recipients email ID
        $name = "Recipient's name"; // Recipient's name
        $mail->AddAddress($emailTo, $name);

        $groupEmail = User::model()->getGroupEmail()->email;
        $groupEmailArray = preg_split('/;/', $groupEmail);
        $groupName = 'Company';
        if (count($groupEmailArray) > 0) {
            for ($i = 0; $i < count($groupEmailArray); $i++) {
                $newEmail = $groupEmailArray[$i];
                $mail->AddAddress($newEmail, $groupName);
            }
        }

        $mail->AddReplyTo($webmaster_email, "Webmaster");
        $mail->WordWrap = 50; // set word wrap
        //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
        // $mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment

        $mail->IsHTML(true); // send as HTML
        $mail->Subject = $info['subject'];
        $mail->Body = $info['body']; //HTML Body
        // $mail->AltBody = "This is the body when user views in plain text format"; //Text Body
        if (!$mail->Send()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
